/*
                  KEFKA'S   REVENGE 
                  |=|  /=/    |=|  \=\
                  |=|/=/      |=|  /=/
                  |=|\=\      |=| \=\
                  |=|  \=\    |=|   \=\  .js 		         
                  ==============/
                      BY KEITH LINK   
              EMAIL: delfrickintree@yahoo.com
                 AIM: Thompson1189                                                                               
*/
GetSystemFont().drawText(15,10,"LOADING...");
FlipScreen();

EvaluateScript("clock.js");
EvaluateScript("properties.js");
EvaluateScript("scenes01_00_prechase.js");
EvaluateScript("scenes01_01_chasecourtjail.js");
EvaluateScript("scenes01_02_stuff_stfu.js");
EvaluateScript("subevents.js");
EvaluateScript("menu.js");
EvaluateScript("bootmaps.js");
EvaluateScript("guitarbattle.js");

var evilcackle = LoadSound("KRlaugh.wav");	//the most crucial part of this game!
var window = LoadWindowStyle("reddishfetish.rws");
var window2 = LoadWindowStyle("blueishseethruish.rws");
var fakewindow = LoadImage("jewtheblue.bmp");
var alphagrad = LoadImage("alphagrad.png");
var font = LoadFont("FF6font.rfn");
var font2 = LoadFont("FF6font.rfn");
var pointer = LoadImage("thefinger.png");
//var dooropen = LoadSound("  .wav");
//var savepoint = LoadAnimation("Savepoint.mng");

var jumpasser = LoadSound("jump_sfx.wav");
var dooropen = LoadSound("door_open_sfx.wav");
var doorclose = LoadSound("door_close_sfx.wav");
var save = LoadSound("save_sfx.wav");
var curse = LoadSound("select_sfx.wav");

var globalcrap = [];

function getter(what)
{
	if (!globalcrap[what])
	{
		var type = what.substr(what.length-3, what.length);
		if (type=="rss") globalcrap[what] = LoadSpriteset(what);
		if (type=="ogg") globalcrap[what] = LoadSound(what);
		if (type=="wav") globalcrap[what] = LoadSound(what);
		if (type=="mp3") globalcrap[what] = LoadSound(what);
		if (type=="png") globalcrap[what] = LoadImage(what);
		if (type=="bmp") globalcrap[what] = LoadImage(what);
		if (type=="gif") globalcrap[what] = LoadImage(what);
	}
	return globalcrap[what];
}

var thePC = new Object();
	thePC.name = "";
var Kbusy = false;
var checkidle = true;
var idle = false;
var idletime = GetTime();
var idledelay = 7000;
var stairdir = 0;
var climbmode = [false, 1];
var showtheFinger = false;

var talkmode = false;
var talkmarker = 0;
var dontproceed = false;
var nowind = false;
var textdraw = false;
var fading = false;
var dudefading = "";
var fadecol = new Array(0,0,0,255);
var blackout = false;
var theFullText = "";
var theTempText = "";
var justtalked = false;
var subtitleText = false;
var OMGcanIPressEnter = false;
var sec_out_01 = true;		//OMG
var OMGdontNeedToPressEnter = false;
var OMGCANTPressEnter = false;
var maxdelay = false;	//delay before msg auto-closes

var gang = new Object();	//the_enemy
var battlestuff = false;
	//battlestuff = ['setlist01', 'battlebg01.png'...
var eventinprog = false;
var eventmark = 0;
var proceed = true;
var evq = new Array();
var subevq = new Array();
var bevq = new Array();
var beventmark = 0;
var bproceed = true;
var xbo=10, ybo=11;
var xbor=8, ybor=8;
var rfXo=3, rfYo=3;
var winx = xbor;
var winy = ybor;
var renderjunks = [];

var dude = new Object();
var thadir = "";		// for reverting dir after talk
var pandir = ["still", 0, 0];
var thecam = 0;
var sec_out_02 = true;
var thempa = "Albrook.rmp";
var thebgm = 0;
var thebgmname = "";
var originaltime = 0;
var timer = new Clock();
var party = new Array();
var evillaughs = 0;
var money = 0;
var saveable = true;
var saveptbounds = false;
var dispTownsave = false;
var stage = "Demo";
var dispTown = false;	//town name displays onEnTrance
var people = new Array();	//list of entities
var thecouch = 0;
var thefridge = 0;
var thetele = 0;
var chests = [];
var switches = [];
var sprintimer = 0;
var pacecounter = 0;
var prevframe = 0;

var debugable = false;
var boundschecker = false;
var fanceydisplay = true;
var windowstyle = "reddishfetish.rws";
var walking = false;

var key_laugh = KEY_SPACE;
var key_menu = KEY_HOME;
var key_cancel = KEY_BACKSPACE;
var key_debug = KEY_SLASH;
var key_talk = KEY_ENTER;
var key_shoes = KEY_SHIFT;

var fpschoice = 45;

var pcmu = COMMAND_MOVE_NORTH, pcfu = COMMAND_FACE_NORTH;
var pcmr = COMMAND_MOVE_EAST, pcfr = COMMAND_FACE_EAST;
var pcmd = COMMAND_MOVE_SOUTH, pcfd = COMMAND_FACE_SOUTH;
var pcml = COMMAND_MOVE_WEST, pcfl = COMMAND_FACE_WEST;

EvaluateScript("saveload.js");
EvaluateScript("battle.js");
EvaluateScript("miscmap.js");


function game()
{
	if (!IsMapEngineRunning())	//initialize map engine
	{ SetUpdateScript("game();"); thempa="blank.rmp"; MapEngine('blank.rmp', 45); }

	SetRenderScript("rendition();");
	SetUpdateScript("updation();");

		var stretchy = LoadImage("KRTitle_stretchable.bmp");
		var title = LoadAnimation("KRTitle.mng");
		var logo1 = LoadAnimation("DS.mng");
		var logo2 = LoadAnimation("DSflip2.mng");
		var tint = CreateSurface(32,32, CreateColor(0,0,0,75));

		var is_stretched = false;
		var stretch_factor = 0;
		var time01 = GetTime();
		var dontintroaftergame = false;
		var logo2frame = 0;
		var continents = false		//can't use "continue"

		while (GetTime() < time01 + 11000 && !IsKeyPressed(KEY_ENTER))
		{
			if (!is_stretched)
			{
				stretchy.transformBlit(20,124-stretch_factor,  276,124-stretch_factor,  276,124,  20,124);
				stretch_factor++;
				if (stretch_factor == 64) { is_stretched = true; var time04 = GetTime(); }
			}
			else
			{
				if (GetTime() - time04 > 3000) continents = true;
				
				if (logo2frame < 26 && continents)
				{
					logo2.readNextFrame();
					logo2.drawFrame(128,175);
					logo2frame++;
				}
				else if (continents)
				{
					logo1.readNextFrame();
					logo1.drawFrame(128,175);
					font.setColorMask(CreateColor(0,255,0,128));
					font.drawText(70,210, "KR PROJECT: 2001-2004");
				}
				title.drawFrame(21,61);
				tint.blit(128,175);
				title.readNextFrame();
				var time03 = GetTime();
				while(time03 + 60 > GetTime())
				{
					if (IsKeyPressed(KEY_ENTER)) break;
				}
			}
			font.setColorMask(White);
			font.drawText(100,125,"PRESS ENTER");
			
			FlipScreen();
		}
		font.setColorMask(White);
		if (IsKeyPressed(KEY_ENTER))
		{
			dontintroaftergame = true;
			FlipScreen();
			LoadGameMenu();
		}
		if (!dontintroaftergame)	//prevents intro after engine exit
			eventBox["introscene"].play();
}


function StartGame()
{
	//reset everything in case new game is LOADED
	key_laugh = KEY_SPACE;
	key_menu = KEY_HOME;
	key_cancel = KEY_BACKSPACE;
	key_debug = KEY_SLASH;
	key_talk = KEY_ENTER;
	key_shoes = KEY_SHIFT;
	fpschoice = 45;
	init_charstats();
	//reset all inventory quantities
	money = 0;
	evillaughs = 0;
	thecouch = 0;
	thefridge = 0;
	thetele = 0;
	fanceydisplay = true;
	windowstyle = "reddishfetish.rws";
	window = LoadWindowStyle(windowstyle);
	SetUpdateScript('updation();');
	SetRenderScript('rendition();');
	for (var w=0; w<theHUGEeventlist.length; w++)
	{
		eventBox[theHUGEeventlist[w]].happened = false;
		eventBox[theHUGEeventlist[w]].inprog = false;
	}
	var fools = GetPersonList();
	for (var e=0; e<fools.length; e++)
		DestroyPerson(fools[e]);	//holocate
	if (IsKeyPressed(KEY_SLASH))
	{
	var cheaparray = new Array('prechase', 'scene1', 'gimms_scene', 'court_scene', 'jail_scene', 'chase2', 'newhouse', 'kefka_dream1', 'morning_after', 'splits');
	var pointar = 7;
	while (AreKeysLeft()) GetKey();
	var bitchtime = GetTime();
	while (!IsKeyPressed(key_talk) || GetTime() < bitchtime+100)
	{
		ApplyColorMask(Black);
		font.drawText(20,50, "PreChase");
		font.drawText(20,62, "The Chase");
		font.drawText(20,74, "Gimms");
		font.drawText(20,86, "Court Scenes");
		font.drawText(20,98, "Jail Time");
		font.drawText(20,110, "Chase Again");
		font.drawText(20,122, "Open House");
		font.drawText(20,134, "Nightmares");
		font.drawText(20,146, "Wake up");
		font.drawText(20,158, "Do the Splits");
		pointer.blit(5, 50+pointar*12);
		FlipScreen();
		switch (GetKey())
		{
		case KEY_UP: pointar--; break;
		case KEY_DOWN: pointar++; break;
		}
	}
	eventBox[cheaparray[pointar]].play();
	}
	else
	eventBox['prechase'].play();
	//eventBox['scene1'].play();
	//eventBox['jail_scene'].play();
	//eventBox['court_scene'].play(true);
	//eventBox['exag_scene3'].play(true);
	//eventBox['flashback_scene'].play(true);
	//eventBox['gimms_scene'].play(true);
	//eventBox['jail_cont_scene'].play();
	//eventBox['furniture_mission'].play();
	//eventBox['splits'].play();
}


function initGame(notime)
{
	AttachInput(thePC.name);
	AttachCamera(thePC.name);
	SetTalkActivationKey(key_talk);
	SetTalkDistance(4);
	SetUpdateScript("updation();");
	SetRenderScript("rendition();");
	eventinprog = false;
	if (!notime) timer.start();
}

function updation()
{
	/* THE KEYS */	
	if (IsKeyPressed(key_laugh) && !eventinprog && !walking) gocrazy();
	if (IsKeyPressed(key_debug) && !eventinprog) warpmap('Debugroom.rmp',50,50,true);
	if (IsKeyPressed(key_menu) && eventsareclean() && !talkmode && !textdraw) mainmenu();
	//if (IsKeyPressed(KEY_F3)) Abort(ExecuteZoneScript(0));
	if (IsKeyPressed(KEY_F8)) SetMapEngineFrameRate(GetMapEngineFrameRate()+1);
	if (IsKeyPressed(KEY_F7)) SetMapEngineFrameRate(GetMapEngineFrameRate()-10);
	
	if (IsKeyPressed(KEY_F5) && thempa == "Albrook.rmp" && !IsLayerVisible(4))  NightBrook();

	if (climbmode[0] && !IsInputAttached() && !walking){ tilebasement(); if (dudecanclimb()) SetPersonDirection(thePC.name, 'climb'); }

	if (IsInputAttached() && !Kbusy && eventsareclean())
	{
		var inp = GetInputPerson();
		var spd = GetPersonSpeedX(inp);
	// SPRINT SHOES! //
		if (IsKeyPressed(key_shoes) && !climbmode[0] && MovingKeys() && !dudeobstructed(inp))
		{
			if (!sprintimer) sprintimer = GetTime();
			if (sprintimer + 1500 < GetTime())  SetPersonSpeed(inp, 4);
			else SetPersonSpeed(inp, 2);
		// SPEED PACING
			if ( (spd != 1) && (pacecounter+1 % ((spd==4) ? 2 : 4) == 0) && 0 )	//check every 4 frames for 2x speed; every 2 frames for 4x
			{
				if (GetPersonFrame(inp) == prevframe)		//else sphere changed the frame already
				{
					if (prevframe==3) prevframe=0;
					else prevframe++;
					SetPersonFrame(inp, prevframe);
				}
			}	
			pacecounter++;
			if (pacecounter==15) pacecounter=0;
					prevframe = GetPersonFrame(inp);
		}
		else
		{
			if (spd==4 || spd==2) 
				SetPersonSpeed(inp, 1);
			sprintimer = false;
			pacecounter = 0;
		}
			
	
	// ANTI-OBSTRUCT SHOES! //
		if (IsKeyPressed(KEY_CTRL))
			IgnoreTileObstructions(inp, true);
		else if (IsIgnoringTileObstructions(inp))
			IgnoreTileObstructions(inp, false);

		if (!walking) tilebasement();

		if (IsAnyKeyPressed()){idle = false; idletime = GetTime(); }
		else if (!walking && !idle) SetPersonFrame(thePC.name, 0);
		
	// HUH? FINGER! //
		if (IsKeyPressed(KEY_1) && !showtheFinger)	//ADD AFOREST CHECKING
		{ showtheFinger = true; SetDelayScript(50, 'showtheFinger=false;'); }
	}
	
	if (saveptbounds)
		if (GetPersonX(thePC.name) != saveptbounds[0] || GetPersonY(thePC.name) != saveptbounds[1])
			{saveable = false; saveptbounds = false;}
	
	if (pandir[0] != "still")
		panhandle();
		
	/*EVENTS & SUBS*/
	if (eventsareclean()) NPCjunk();
	else if (proceed) eteq();
	
	for (var a=0; a<subevq.length; a++)
	{
		if (subevq[a].inprog && subevq[a].proceed)
		{
			subevq[a].pos++;
			eval(subevq[a].evq[subevq[a].pos]);
		}
	}
	
	/* TALKING (TEXT) EFFECT */
	if (talkmode) thetalkingstuff()
	
	/* IDLE CHECKING */
	if (checkidle && IsInputAttached() && !walking && idletime + idledelay <= GetTime() && eventsareclean() && !climbmode[0])
	{
		idle = true;
		checkidle = false;
		if (thePC.rss == "Kefka.rss")
			idlefunK(Math.floor(Math.random()*8)); //integer < 8
		else if (thePC.rss == "Brown.rss")
			idlefunB(Math.floor(Math.random()*2));
	}

}

function MovingKeys()
{
	if (IsKeyPressed(KEY_UP) || IsKeyPressed(KEY_DOWN) || IsKeyPressed(KEY_LEFT) || IsKeyPressed(KEY_RIGHT))
	return true;
	else return false;
}


function eteq()
{
	if (eventmark >= evq.length)
	{
		evq = new Array();
		eventmark = 0;
		eventinprog = false;
	}
	else
	{
		eval(evq[eventmark]);
		eventmark++;
	}
}

function dudeobstructed(nerd)
{
	var thedir = GetPersonDirection(nerd);
	var thevel = GetPersonSpeedX(nerd);
	if (thedir == "north")
	{
		if (IsPersonObstructed(nerd, GetPersonX(nerd), GetPersonY(nerd)-thevel))
			return true;
	}
	else if (thedir == "south")
	{
		if (IsPersonObstructed(nerd, GetPersonX(nerd), GetPersonY(nerd)+thevel))
			return true;
	}
	else if (thedir == "east")
	{
		if (IsPersonObstructed(nerd, GetPersonX(nerd)+thevel, GetPersonY(nerd)))
			return true;
	}
	else if (thedir == "west")
	{
		if (IsPersonObstructed(nerd, GetPersonX(nerd)-thevel, GetPersonY(nerd)))
			return true;
	}
	return false;
}

function NPCjunk()
{
	if (thePC.name=="") return;	//eventinprog but not *really* eventinprog
	var kpx = GetPersonX(thePC.name);
	var kpy = GetPersonY(thePC.name);
	if (people)
	{
	for (var p=0; p<people.length; p++)
	{
		if (people[p] != thePC.name && people[p] != dude.name)
		{	/* If the npc is near pc... otherwise avoid all this*/
		if ((Math.abs(kpx - GetPersonX(people[p])) <= 20) && (Math.abs(kpy - GetPersonY(people[p])) <= 20))
		{
			if (boundschecker) boundschecker = "font.drawText(1,26,'" + people[p] + "'); font.drawText(1,37,'" + GetPersonX(people[p]) + "," + GetPersonY(people[p]) + "'); font.drawText(1,48,'" + kpx + "," + kpy + "');";
			if (dudeobstructed(people[p])) QueuePersonCommand(people[p], COMMAND_WAIT, false);
		}
		}
		else if (people[p]==dude.name && !dude.toobusy)// && (talkmode || textdraw))
			QueuePersonCommand(dude.name, COMMAND_WAIT, false);
		} //end people check
	}
}

function tilebasement()
{			//difference of where you are and where you should be
	var difX = (GetPersonX(thePC.name) - (Math.floor((GetPersonX(thePC.name)-7)/8)*8+7))/GetPersonSpeedX(thePC.name);
	var difY = (GetPersonY(thePC.name) - (Math.floor((GetPersonY(thePC.name)-7) /8)*8+7))/GetPersonSpeedY(thePC.name);
	var SPX = GetPersonSpeedX(thePC.name);
	var SPY = GetPersonSpeedY(thePC.name);
	var fullstep = (stairdir) ? 8 : 0;
	if (IsKeyPressed(KEY_UP))
	{
		walking=true; DetachInput(); if (!climbmode[0]) SetPersonDirection(thePC.name, "north");
											else {if (dudecanclimb()) SetPersonDirection(thePC.name, 'climb'); SetPersonLayer(thePC.name, climbmode[1]);}
		for (var w=0; w<(8+fullstep)/SPY+difY; w++)
		{	if (!climbmode[0]){
			if (stairdir==1){ SetPersonDirection(thePC.name, "east"); QueuePersonCommand(thePC.name, COMMAND_MOVE_EAST, true);}
			else if (stairdir==2){ SetPersonDirection(thePC.name, "west"); QueuePersonCommand(thePC.name, COMMAND_MOVE_WEST, true);}
			else if (IsKeyPressed(KEY_RIGHT)) QueuePersonCommand(thePC.name, COMMAND_MOVE_EAST, true);
			else if (IsKeyPressed(KEY_LEFT)) QueuePersonCommand(thePC.name, COMMAND_MOVE_WEST, true);}
			QueuePersonCommand(thePC.name, COMMAND_MOVE_NORTH, false); 
		}
		QueuePersonScript(thePC.name, "trigtest(); if (!Kbusy && !climbmode[0]) AttachInput(thePC.name); walking=false; ", false);
	}
	else if (IsKeyPressed(KEY_DOWN))
	{
		walking=true; DetachInput(); if (!climbmode[0]) SetPersonDirection(thePC.name, "south");
											else {if (thePC.name=='Kefka') SetPersonDirection(thePC.name, 'climb'); SetPersonLayer(thePC.name, climbmode[1]);}
		for (var w=0; w<(8+fullstep)/SPY-difY; w++)
		{	if (!climbmode[0]){
			if (stairdir==1){ SetPersonDirection(thePC.name, "west"); QueuePersonCommand(thePC.name, COMMAND_MOVE_WEST, true);}
			else if (stairdir==2){ SetPersonDirection(thePC.name, "east"); QueuePersonCommand(thePC.name, COMMAND_MOVE_EAST, true);}
			else if (IsKeyPressed(KEY_RIGHT)) QueuePersonCommand(thePC.name, COMMAND_MOVE_EAST, true);
			else if (IsKeyPressed(KEY_LEFT)) QueuePersonCommand(thePC.name, COMMAND_MOVE_WEST, true);}
			QueuePersonCommand(thePC.name, COMMAND_MOVE_SOUTH, false);
		}
		QueuePersonScript(thePC.name, "trigtest(); if (!Kbusy && !climbmode[0]) AttachInput(thePC.name); walking=false;", false);
	}
	else if (IsKeyPressed(KEY_RIGHT) && !climbmode[0])
	{
		walking=true; DetachInput(); SetPersonDirection(thePC.name, "east");
		for (var w=0; w<8/SPX-difX; w++)
		{
				if (stairdir==1) QueuePersonCommand(thePC.name, COMMAND_MOVE_NORTH, true);
			 else if (stairdir==2) QueuePersonCommand(thePC.name, COMMAND_MOVE_SOUTH, true);
			QueuePersonCommand(thePC.name,COMMAND_MOVE_EAST,false);
		}
		QueuePersonScript(thePC.name, "if (!Kbusy) AttachInput(thePC.name); walking=false;", false);
		QueuePersonScript(thePC.name, "if (climbmode[0]) DetachInput();", false);
	}
	else if (IsKeyPressed(KEY_LEFT) && !climbmode[0])
	{
		walking=true; DetachInput(); SetPersonDirection(thePC.name, "west");
		for (var w=0; w<8/SPX+difX; w++)
		{
				if (stairdir==1) QueuePersonCommand(thePC.name, COMMAND_MOVE_SOUTH, true);
			 else if (stairdir==2) QueuePersonCommand(thePC.name, COMMAND_MOVE_NORTH, true);
			QueuePersonCommand(thePC.name,COMMAND_MOVE_WEST,false);
		}
		QueuePersonScript(thePC.name, "trigtest(); if (climbmode[0]) anothereight(); else {if (!Kbusy) AttachInput(thePC.name); walking=false;}", false);
	}
	

	
	if (IsKeyPressed(KEY_F6))
	{
		SetPersonX(thePC.name, GetPersonX(thePC.name)+difX);
		SetPersonY(thePC.name, GetPersonY(thePC.name)+difY);
		stairdir = 0;
		walking = false;
	}
}


function trigtest()
{
	if (IsTriggerAt(GetPersonX(thePC.name), GetPersonY(thePC.name), GetPersonLayer(thePC.name)) && (climbmode[0] || GetPersonDirection(thePC.name)=='west'))	//might not need additional conditional
		ExecuteTrigger(GetPersonX(thePC.name),GetPersonY(thePC.name),GetPersonLayer(thePC.name));
}
	
function anothereight()
{
	if (climbmode[0] && GetPersonDirection(thePC.name)=="west" && walking)		//moves another 8 pix to hit ladder
	{
		for (var w=0; w<8/GetPersonSpeedX(thePC.name); w++)
			QueuePersonCommand(thePC.name,COMMAND_MOVE_WEST,false);
		QueuePersonScript(thePC.name, "walking=false;", false);
	}
}

function dudecanclimb()
{	//more sprites in future
	if (charstats[party[0]].rss=='Kefka.rss' || charstats[party[0]].rss=='Brown.rss') return true;
	else return false;
}

function talkjunk(junk)
{
	if (!justtalked)
	{
		if (!talkmode)
		{
			for (var a=0; a<subevq.length; a++) if (subevq[a].inprog) subevq[a].proceed = false;
			if (eventsareclean() && !gang.pause4event)
			{
				if (!dude.name){ dude = eval(GetCurrentPerson());
				thadir = GetPersonDirection(dude.name);}
				SetPersonFrame(thePC.name,0);	//no mid-stride!
				if (dude.face)
				{
					var kdir = GetPersonDirection(thePC.name);
					if (kdir == "north") SetPersonDirection(dude.name, "south");
					if (kdir == "south") SetPersonDirection(dude.name, "north");
					if (kdir == "east") SetPersonDirection(dude.name, "west");
					if (kdir == "west") SetPersonDirection(dude.name, "east");
					SetPersonFrame(dude.name, 0);
				}
				if (junk != undefined)	theFullText = junk;
				else
				{
					if (dude.incremental)
					{
						theFullText = eval(dude.name+".talk"+dude.diamark);
						if (dude.firstonce){ if (dude.diamark==1) dude.diamark++;}
						else dude.diamark++;
						if (!eval(dude.name + ".talk" + dude.diamark)) dude.diamark = 1;
						if (dude.talkrand)
						{		//get number of talks
							for (ghey=1; true; ghey++) if (!eval(dude.name + ".talk" + ghey)) break;
							theFullText = eval(dude.name+".talk"+ (Math.floor(Math.random()*(ghey-1))+1));
						}
					}
					else theFullText = eval(dude.name +".talk"+dude.diamark);
				}
				Kbusy = true;	
				if (!OMGdontNeedToPressEnter && !maxdelay) DetachInput();
			}
			else theFullText = junk;
			if (eventinprog) proceed = false;
			if (gang.pause4event) bproceed = false;
			talkmode = true;
			textdraw = true;
			checkidle = false;
		}
	}
}

function subtitle(eng)
{
	if (!justtalked) subtitleText = eng;
}

function thetalkingstuff()
{		
	if (talkmarker >= theFullText.length)	//when full message is displayed..
	{
		//only do this once
		if (sec_out_01)
		{	sec_out_01 = false;
			SetDelayScript( ((eventinprog) ? 13 : 8), "OMGcanIPressEnter = true;");
			if (maxdelay){ OMGdontNeedToPressEnter=false; SetDelayScript(maxdelay, "if (!sec_out_01){OMGdontNeedToPressEnter = true; OMGCANTPressEnter=false;}");}
		}

		if (AreKeysLeft() && dude.choice)
		{
			var OMG = GetKey();
			if (OMG==KEY_UP){ if (dude.choice3) {if (dude.pointah>0) dude.pointah--;} else dude.pointah=0;}
			if (OMG==KEY_DOWN){ if (dude.choice3) {if (dude.pointah<2) dude.pointah++;} else dude.pointah=1;}
		}
		if (OMGcanIPressEnter && !OMGCANTPressEnter && (IsKeyPressed(key_talk) || OMGdontNeedToPressEnter)) 
		{			//reset everything!
			justtalked = true;
			talkmarker=0;
			theFullText = "";
			theTempText = "";
			subtitleText = false;
			talkmode = false;
			textdraw = false;
			Kbusy = false;
			OMGcanIPressEnter = false;
			OMGdontNeedToPressEnter = false;
			sec_out_01 = true;
			if (eventsareclean() && !gang.pause4event)
			{
				
				if (!dude.incremental && eval(dude.name + ".talk" + ++dude.diamark))	//if has more to say..
				{
					theFullText = eval(dude.name+".talk"+dude.diamark);
					SetDelayScript(10, "talkmode = true; textdraw = true;");
				}
				else
				{
					while (AreKeysLeft()) GetKey();
					if (dude.choice)
					{
						justtalked = false;
						talkmode = false;
						//dude.choice = false;
						if (dude.pointah){	if (dude.no)	dude.no();	else resetTalk(); }
						else 			{	if (dude.yes)	dude.yes();	}
					}
					else
					{
						if (dude.shop) dude.shop();
						SetDelayScript(1, "justtalked = false;");
						if (!dude.toobusy) SetPersonDirection(dude.name, thadir);
						if (!dude.incremental) dude.diamark = 1;
						dude = new Object();
						if (!OMGdontNeedToPressEnter) AttachInput(thePC.name);
					}
				}
				checkidle = true;
				idletime = GetTime();
			}
			else
			{
				justtalked = false;
				if (!dontproceed) proceed = true;		//intro,subevents
				dontproceed = false;
				for (var a=0; a<subevq.length; a++) if (subevq[a].inprog) subevq[a].proceed = true;
				if (gang.pause4event) bproceed = true;
				dude = new Object();
			}
		}
	}
	else	//continue [typing] the dialogue
	{
		if (theFullText.substr(talkmarker, 2) == "/w")		//CHECK FOR HESITATION
		{
			talkmode = false;
			justtalked = true; 	//so they can't retalk during hesitation
			SetDelayScript(10, "talkmode = true; justtalked=false;");
			talkmarker+=2;
		}
		else
		{
			theTempText += theFullText.charAt(talkmarker);
			talkmarker++;
			if (talkmarker > 15 && IsKeyPressed(key_talk) && !OMGCANTPressEnter)	//if you don't care
			{
				for (; talkmarker<theFullText.length; talkmarker++)
				{
					if (theFullText.substr(talkmarker, 2) == "/w") talkmarker++
					else theTempText += theFullText.charAt(talkmarker);
				}
			}
		}
	}

}

function talkagain(smack)
{
	theFullText = smack;
	justtalked = true;
	dude.choice = false;
	SetDelayScript(5, "talkmode = true; textdraw = true;");
}

function resetTalk()
{
	if (dude.shop) dude.shop();
	SetDelayScript(1, "justtalked = false;");
	if (!dude.toobusy) SetPersonDirection(dude.name, thadir);
	if (!dude.incremental) dude.diamark = 1;
	dude = new Object();
	if (!OMGdontNeedToPressEnter) AttachInput(thePC.name);
}

function eventsareclean()
{
	for (var a=0; a<subevq.length; a++) if (subevq[a].inprog && !subevq[a].clean) return false;	//clean: subevents that dont mess with sheeit
	if (eventinprog) { if (eventinprog=="pause") return true; else return false; }
	return true;
}

function rendition()
{
	var box1 = GrabImage(0,0,320,59);
	var box2 = GrabImage(0,60,320,59);
	var box3 = GrabImage(0,120,320,59);
	var box4 = GrabImage(0,180,320,59);
	
	box1.transformBlit(0,0,      320,0,      320,29,     0,29);
	box2.transformBlit(0,30,      320,30,      320,69,     0,69);
	box3.transformBlit(0,70,    320,70,    320,149,   0,149);
	box4.transformBlit(0,150,  320,150,   320,240,    0, 240);
	
	
	if (blackout) ApplyColorMask(CreateColor(fadecol,fadecol,fadecol,255));
	if (textdraw)
	{
		if (nowind)
		font.drawTextBox(winx,winy,305,190,0, theTempText);
		else {window.drawWindow(winx, winy, 310, 60); font.drawTextBox(winx+3, winy, 310, 60, 0, theTempText);}
	}
	
	if (false)//fading)
	{
		blackout = false;
		if (fading == "in")
		{
			thefade -= 25;
			ApplyColorMask(CreateColor(fadecol,fadecol,fadecol,thefade));
			if (thefade < 10)
			{
				fading = false;
				proceed = true;
				thefade = 255;
			}
		}
		else if (fading == "out")
		{
			thefade += 25;
			ApplyColorMask(CreateColor(fadecol,fadecol,fadecol,thefade));
			if (thefade > 255)
			{
				fading = false;
				proceed = true;
				thefade = 255;
			}
		}
		else if (fading == "person_out")
		{
			thefade -= 5;
			SetPersonMask(dudefading, CreateColor(255,255,255,thefade));
			if (thefade < 10)
			{
				fading = false;
				DestroyPerson(dudefading);
				proceed = true;
				thefade = 255;
			}
		}

	}
	if (boundschecker) eval(boundschecker);
}



function retard(eman,rss,sheeit)
{
	this.name = eman;
	this.step = 0;
	this.mark = 0;
	this.dirs = new Array('w');
	CreatePerson(eman, rss, sheeit);
}

function npcrap(eman)
{
	this.name = eman;
	this.step = 0;
	this.mark = 0;
	this.face = true;
	this.dirs = new Array('w');
}



/* MISC MAP SCRIPTS */


function warpmap(map,xset,yset)
{
	if (!eventinprog)
	{
		idle = false;
		eprep();
		ateq("");
		ateq("fadeOutScreen();");
		ateq("blackout = true;");
		ateq("ChangeMap('" + map + "');");
		ateq("thempa = '" + map + "';");
		if (xset != undefined && yset != undefined)
			ateq("SetPersonX('Kefka'," + xset + "); SetPersonY('Kefka'," + yset + ");");
		ateq("SetPersonDirection(GetInputPerson(), 'south');");
		ateq("fadeInScreen();");
		ateq("idletime = GetTime(); checkidle = true;");
		ateq("eventinprog = false;");
		eventinprog = true;
	}
}


function gocrazy()
{
	if (!Kbusy)
	{
		Kbusy = true;
		evilcackle.play(false);
		evillaughs++;
		DetachInput();
		idle = false;
		checkidle = false;
		SetPersonDirection("Kefka", "laugh");
		for (i=0; i<10; i++)
		{
			SetDelayScript(i*8, "SetPersonFrame('Kefka'," + ((i % 2 == 0) ? 0 : 1) + ");");
		}
		SetDelayScript(96, "Kbusy = false;");
		if (!eventinprog) SetDelayScript(96, "SetPersonDirection('Kefka', 'south'); AttachInput('Kefka'); idletime = GetTime(); checkidle = true;");
	}
}




function ateq(bagawk)
{
	evq[evq.length] = bagawk;
}
	

function eprep()
{
	eventinprog = false;
	eventmark = 0 ;
	evq = new Array();
}


function idlefun0()
{
	if (moving==0 && idle) SetPersonDirection('Kefka', 'south');
	SetDelayScript(50,   "if (moving==0 && idle) SetPersonDirection('Kefka', 'lookwest');");
	SetDelayScript(100, "if (moving==0 && idle) SetPersonDirection('Kefka', 'south');");
	SetDelayScript(150, "if (moving==0 && idle) SetPersonDirection('Kefka', 'lookeast');");
	SetDelayScript(200, "if (moving==0 && idle){SetPersonDirection('Kefka', 'south'); idletime=GetTime();} idle=false; checkidle=true;");
}

function idlefun1()
{
	if (moving==0 && idle) SetPersonDirection('Kefka', 'south');
	SetDelayScript(50,   "if (moving==0 && idle) SetPersonDirection('Kefka', 'scratch'); SetPersonFrame('Kefka', 1);");
	SetDelayScript(75, "if (moving==0 && idle) SetPersonFrame('Kefka', 0);");
	SetDelayScript(120, "if (moving==0 && idle){SetPersonDirection('Kefka', 'south'); SetPersonFrame('Kefka', 0); idletime=GetTime();} idle=false; checkidle=true;");
}

function idlefun2()
{
	if (moving==0 && idle) SetPersonDirection('Kefka', 'south');
	SetDelayScript(50,   "if (moving==0 && idle) SetPersonDirection('Kefka', 'nono');");
	SetDelayScript(70, "if (moving==0 && idle) SetPersonFrame('Kefka', 1);");
	SetDelayScript(90, "if (moving==0 && idle) SetPersonFrame('Kefka', 0);");
	SetDelayScript(110, "if (moving==0 && idle) SetPersonFrame('Kefka', 1);");
	SetDelayScript(130, "if (moving==0 && idle) SetPersonFrame('Kefka', 0);");
	SetDelayScript(150, "if (moving==0 && idle) SetPersonFrame('Kefka', 1);");
	SetDelayScript(170, "if (moving==0 && idle){SetPersonDirection('Kefka', 'south'); SetPersonFrame('Kefka', 0); idletime=GetTime();} idle=false; checkidle=true;");
}

function idlefun3()
{
	if (moving==0 && idle) SetPersonDirection('Kefka', 'south');
	SetDelayScript(50,   "if (moving==0 && idle) SetPersonDirection('Kefka', 'crouch');");
	SetDelayScript(100, "if (moving==0 && idle) SetPersonDirection('Kefka', 'owch');");
	SetDelayScript(275, "if (moving==0 && idle) SetPersonDirection('Kefka', 'crouch');");
	SetDelayScript(300, "if (moving==0 && idle){SetPersonDirection('Kefka', 'south'); SetPersonFrame('Kefka', 0); idletime=GetTime();} checkidle=true;");
}

function idlefun4()
{
	if (moving==0 && idle) SetPersonDirection('Kefka', 'south');
	SetDelayScript(50,   "if (moving==0 && idle) SetPersonDirection('Kefka', 'blink');");
	SetDelayScript(70,   "if (moving==0 && idle) SetPersonDirection('Kefka', 'south');");
	SetDelayScript(90,   "if (moving==0 && idle) SetPersonDirection('Kefka', 'blink');");
	SetDelayScript(110, "if (moving==0 && idle) SetPersonDirection('Kefka', 'south');");
	SetDelayScript(130, "if (moving==0 && idle) SetPersonDirection('Kefka', 'blink');");
	SetDelayScript(150, "if (moving==0 && idle){SetPersonDirection('Kefka', 'south'); SetPersonFrame('Kefka', 0); idletime=GetTime();} idle=false; checkidle=true;");
}

function idlefun5()
{
	if (moving==0 && idle) SetPersonDirection('Kefka', 'south');
	SetDelayScript(50,   "if (moving==0 && idle) SetPersonDirection('Kefka', 'anger');");
	SetDelayScript(70,   "if (moving==0 && idle) SetPersonDirection('Kefka', 'stickup');");
	SetDelayScript(90,   "if (moving==0 && idle) SetPersonDirection('Kefka', 'anger');");
	SetDelayScript(110, "if (moving==0 && idle) SetPersonDirection('Kefka', 'stickup');");
	SetDelayScript(130, "if (moving==0 && idle) SetPersonDirection('Kefka', 'anger');");
	SetDelayScript(150, "if (moving==0 && idle) SetPersonDirection('Kefka', 'stickup');");
	SetDelayScript(170, "if (moving==0 && idle) SetPersonDirection('Kefka', 'anger');");
	SetDelayScript(190, "if (moving==0 && idle){SetPersonDirection('Kefka', 'south'); SetPersonFrame('Kefka', 0); idletime=GetTime();} idle=false; checkidle=true;");
}

function idlefun6()
{
	if (moving==0 && idle) SetPersonDirection('Kefka', 'south');
	SetDelayScript(50,   "if (moving==0 && idle) SetPersonDirection('Kefka', 'looksouth');");
	SetDelayScript(225, "if (moving==0 && idle){SetPersonDirection('Kefka', 'south'); SetPersonFrame('Kefka', 0); idletime=GetTime();} checkidle=true;");
}

function idlefun7()
{
	if (moving==0 && idle) SetPersonDirection('Kefka', 'south');
	SetDelayScript(50,   "if (moving==0 && idle) SetPersonDirection('Kefka', 'shocked');");
	SetDelayScript(100, "if (moving==0 && idle){SetPersonDirection('Kefka', 'south'); SetPersonFrame('Kefka', 0); idletime=GetTime();} checkidle=true;");
}
	

/*	FUNCTIONS CALLED REPEATEDLY (update/render)	*/

function camerapanx(dest_x,speed)
{
	if (GetCameraX() < dest_x) pandir = "right";
	else pandir = "left";
	
	SetCameraX(GetCameraX() + ((pandir=="left") ? -speed : speed));
	
	if (pandir == "left")
	{
		if (GetCameraX() <= dest_x)
		{
			proceed = true;
			SetUpdateScript("updation();");
		}
		else
			SetUpdateScript("camerapanx(" + dest_x + "," + speed + "); updation();");
	}
	else if (pandir == "right")
	{
		if (GetCameraX() >= dest_x)
		{
			proceed = true;
			SetUpdateScript("updation();");
		}
		else
			SetUpdateScript("camerapanx(" + dest_x + "," + speed + "); updation();");
	}

}


function camerapany(dest_y,speed)
{
	if (GetCameraY() < dest_y) pandir = "down";
	else pandir = "up";
	
	SetCameraY(GetCameraY() + ((pandir=="up") ? -speed : speed));
	
	if (pandir == "up")
	{
		if (GetCameraY() <= dest_y)
		{
			proceed = true;
			SetUpdateScript("updation();");
		}
		else
		SetUpdateScript("camerapany(" + dest_y + "," + speed + "); updation();");
	}
	else if (pandir == "down")
	{
		if (GetCameraY() >= dest_y)
		{
			if (introscene.inprog) proceed = true;	//find an alternative or something
			SetUpdateScript("updation();");
		}
		else
		SetUpdateScript("camerapany(" + dest_y + "," + speed + "); updation();");
	}
}

function camerapand(dest_x,dest_y,speed)
{
	        if (GetCameraX() > dest_x && GetCameraY() > dest_y) pandir = "ul";
	else if (GetCameraX() > dest_x && GetCameraY() < dest_y) pandir = "dl";
	else if (GetCameraX() < dest_x && GetCameraY() > dest_y) pandir = "ur";
	else if (GetCameraX() < dest_x && GetCameraY() < dest_y) pandir = "dr";

	SetCameraX(GetCameraX() + ((pandir=="dl" || pandir=="ul") ? -speed : speed));
	SetCameraY(GetCameraY() + ((pandir=="dl" || pandir=="dr") ? speed : -speed));
	
	if (pandir == "dl")
	{
		if (GetCameraX() <= dest_x && GetCameraY() >= dest_y)
		{
			proceed = true;
			SetUpdateScript("updation();");
		}
		else
		SetUpdateScript("camerapand(" + dest_x + "," + dest_y + "," + speed + "); updation();");
	}
	else if (pandir == "ul")
	{
		if (GetCameraX() <= dest_x && GetCameraY() <= dest_y)
		{
			proceed = true;
			SetUpdateScript("updation();");
		}
		else
		SetUpdateScript("camerapand(" + dest_x + "," + dest_y + "," + speed + "); updation();");
	}
	else if (pandir == "dr")
	{
		if (GetCameraX() >= dest_x && GetCameraY() >= dest_y)
		{
			proceed = true;
			SetUpdateScript("updation();");
		}
		else
		SetUpdateScript("camerapand(" + dest_x + "," + dest_y + "," + speed + "); updation();");
	}
	else if (pandir == "dr")
	{
		if (GetCameraX() <= dest_x && GetCameraY() >= dest_y)
		{
			proceed = true;
			SetUpdateScript("updation();");
		}
		else
		SetUpdateScript("camerapand(" + dest_x + "," + dest_y + "," + speed + "); updation();");
	}

}


function fadeOutScreen()
{
	proceed = false;
	thefade = 0;
	fading = "out";
}

function fadeInScreen()
{
	proceed = false;
	fading = "in";
}


function fadePersonOut(dude)
{
	proceed = false;
	fading = "person_out";
	dudefading = dude;
}


function walkgay(guy, dir)
{
	
	switch (dir)
	{		
		case ("l"):
		{
			QueuePersonCommand(guy.name, COMMAND_MOVE_WEST, false);
			if (guy.mark >= 16)
			{
				guy.step++;
				guy.mark = 0;				
			}
			else guy.mark++;
			break;
		}
	
		case ("r"):
		{
			QueuePersonCommand(guy.name, COMMAND_MOVE_EAST, false);
			if (guy.mark >= 16)
			{
				guy.step++;
				guy.mark = 0;
			}
			else guy.mark++;
			break;
		}
		case ("u"):
		{
			QueuePersonCommand(guy.name, COMMAND_MOVE_NORTH, false);
			if (guy.mark >= 16)
			{
				guy.step++;
				guy.mark = 0;
			}
			else guy.mark++;
			break;
		}
		case ("d"):
		{
			QueuePersonCommand(guy.name, COMMAND_MOVE_SOUTH, false);
			if (guy.mark >= 16)
			{
				guy.step++;
				guy.mark = 0;
			}
			else guy.mark++;
			break;
		}
		case ("w"):
		{
			QueuePersonCommand(guy.name, COMMAND_WAIT, false);
			if (guy.mark >= 16)
			{
				guy.step++;
				guy.mark = 0;
			}
			else guy.mark++;
			break;
		}
		case ("fu"):
		{
			QueuePersonCommand(guy.name, COMMAND_FACE_NORTH, false);
			guy.step++;
			break;
		}
		case ("fl"):
		{
			QueuePersonCommand(guy.name, COMMAND_FACE_WEST, false);
			guy.step++;
			break;
		}
		case ("fr"):
		{
			QueuePersonCommand(guy.name, COMMAND_FACE_EAST, false);
			guy.step++;
			break;
		}
		case ("fd"):
		{
			QueuePersonCommand(guy.name, COMMAND_FACE_SOUTH, false);
			guy.step++;
			break;
		}
		case ("ul"):
		{
			QueuePersonCommand(guy.name, COMMAND_MOVE_NORTH, false);
			QueuePersonCommand(guy.name, COMMAND_MOVE_WEST, false);
			if (guy.mark >= 16)
			{
				guy.step++;
				guy.mark = 0;
			}
			else guy.mark++;
			break;
		}
		case ("ur"):
		{
			QueuePersonCommand(guy.name, COMMAND_MOVE_NORTH, false);
			QueuePersonCommand(guy.name, COMMAND_MOVE_EAST, false);
			if (guy.mark >= 16)
			{
				guy.step++;
				guy.mark = 0;
			}
			else guy.mark++;
			break;
		}
		case ("dl"):
		{
			QueuePersonCommand(guy.name, COMMAND_MOVE_SOUTH, false);
			QueuePersonCommand(guy.name, COMMAND_MOVE_WEST, false);
			if (guy.mark >= 16)
			{
				guy.step++;
				guy.mark = 0;
			}
			else guy.mark++;
			break;
		}
		case ("dr"):
		{
			QueuePersonCommand(guy.name, COMMAND_MOVE_SOUTH, false);
			QueuePersonCommand(guy.name, COMMAND_MOVE_EAST, false);
			if (guy.mark >= 16)
			{
				guy.step++;
				guy.mark = 0;
			}
			else guy.mark++;
			break;
		}
		default:
		{
			QueuePersonScript(guy.name, dir, false);
			guy.step++;
			break;
		}
		
		}	//end switch
	
}